<template>
    <div class="api-debug">
        <div style="padding: 10px 0;height: 30px;background: rgba(97, 175, 254, .1);margin: 5px 0;">
            <span class="method forbid-select">{{ apiInfo.method?.toUpperCase() }}</span>
            <span class="url">{{ apiInfo.url }}</span>
            <span class="method run cursor-pointer forbid-select" @click="run">发送</span>
        </div>
        <el-scrollbar style="width: 100%;height: calc(100% - 80px);">
            <el-table :data="apiInfo.parameters" border header-cell-class-name="el-table-header-cell"
                cell-class-name="el-table-cell" class="e-page" ref="tableRef">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="参数名称" width="200" />
                <el-table-column prop="schema.type" label="数据类型" width="200">
                    <template #default="scope">
                        <span>{{ firstUpperCase(scope.row.schema?.type) + (scope.row.schema?.format ? "(" +
                            scope.row.schema.format + ")" : "") }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="value" label="参数值" min-width="400">
                    <template #default="scope">
                        <el-input v-model="scope.row.paramValue" :placeholder="scope.row.description"
                            :class="`input-auto-resize ${scope.row.required ? 'query-required' : ''}`" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100px">
                    <template #default="scope">
                        <el-button type="danger" :icon="Delete" circle class="button-auto-resize"
                            @click="removeParams(scope)" />
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin: 10px 0; ">
                <span style="display: inline-block;width: 100px;">响应内容</span>
                <span style="display: inline-block;width: calc(100% - 100px);text-align: right;" v-if="showResponse">
                    <span :style="`color:${code === 200 ? 'rgba(0,0,0)' : 'red'}`">响应码:{{ code }}</span>
                    <span style="padding: 0 5px;">耗时:{{ cost }}ms</span>
                    <span style="padding: 0 5px;">大小:{{ size }}</span>
                </span>
            </div>
            <div style="border:1px solid rgba(190, 190, 190, 0.5);border-radius: 4px;margin-top: 10px;height: 500px;">
                <aceEditor v-model="response" style="height: 100%;" :options="aceOptions" />
            </div>
        </el-scrollbar>
    </div>
</template>

<script setup>
import router from '@/router'
import instance from "@/pinia"
import { Delete } from "@element-plus/icons-vue"
import { useRequest, useElLoading, useElMessage } from "@usehook"
import { formatSize, formatJson, deepCopy, firstUpperCase } from "@/utils/tools"

const { mainStore } = instance
let apiInfo = $ref({})
let response = $ref("")
const tableRef = $ref(null)
let size = $ref(0)
let cost = $ref(0)
let code = $ref(200)
let showResponse = $ref(false)
const aceOptions = { lang: 'json', fontSize: 16, readOnly: true }

const { loading: elLoading, close } = useElLoading({ text: "正在查询数据...", target: ".api-debug", manual: true, delay: 10 })

const run = () => {
    const params = {}
    for (let p of tableRef.getSelectionRows()) {
        params[p.name] = p.paramValue || null
    }

    for (let p of apiInfo.parameters.filter(p => p.required)) {
        if (!params[p.name]) {
            useElMessage.error(`参数[ ${p.name} ]不能为空`)
            return
        }
    }

    const start = new Date().getTime()
    elLoading()
    useRequest[apiInfo.method](apiInfo.url, params).then(res => {
        showResponse = true
        response = formatJson(res)
        size = formatSize(JSON.stringify(res).length)
        cost = (new Date().getTime() - start)
    }).catch((res) => {
        showResponse = true
        response = formatJson(res)
        size = formatSize(JSON.stringify(res).length)
        cost = (new Date().getTime() - start)
        code = res.status
    }).finally(() => {
        close()
    })
}

const removeParams = (scope) => {
    const index = apiInfo.parameters.findIndex(p => p.name === scope.row.name)
    apiInfo.parameters.splice(index, 1)
}

onMounted(() => {
    apiInfo = deepCopy(mainStore.getUrlMap[router.currentRoute.value.path])
    if (apiInfo.parameters) tableRef.toggleAllSelection()
})

</script>


<style>
.api-debug {
    padding: 10px;
    height: 100%;
}

.api-debug .method {
    display: inline-flex;
    width: 100px;
    background: #61affe;
    height: 100%;
    justify-content: center;
    align-items: center;
    border-radius: 4px;
    margin-left: 10px;
    color: white;
}

.api-debug .run {
    margin-left: 0;
    margin-right: 10px;
}

.api-debug .url {
    display: inline-flex;
    width: calc(100% - 240px);
    height: 100%;
    padding-left: 20px;
}

.api-debug .query-required .el-input__wrapper {
    box-shadow: 0 0 0 1px rgba(255, 0, 0, .3) inset;

}
</style>